package com.moss.cloud.auth.biz.exception;

import com.moss.cloud.common.core.model.Result;
import com.moss.cloud.common.core.utils.EnumsUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;


/**
 * Response异常控制器
 * @author 瑾年
 * @data 2023年3月6
 */
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    public ResponseEntity<Object> translate(Exception e){
       return this.doException(e);
    }
    private ResponseEntity doException(Exception e){
        if(e instanceof OAuth2Exception){
            OAuth2Exception oAuth2Exception = (OAuth2Exception) e;
            return ResponseEntity
                .status(oAuth2Exception.getHttpErrorCode())
                .body(new CustomOauthException(oAuth2Exception));
        }
        if(e instanceof InternalAuthenticationServiceException){
            InternalAuthenticationServiceException internalAuthenticationServiceException = (InternalAuthenticationServiceException) e;
            AuthErrorType authErrorType = EnumsUtils.getEnumObject(AuthErrorType.class,
                    x -> x.getCode().equals(internalAuthenticationServiceException.getMessage())).get();
            return ResponseEntity
                    .status(400)
                    .body(Result.fail(authErrorType));
        }
        return ResponseEntity.ok().build();
    }
}
